# coding:utf-8
import requests
from hashlib import md5


class Verify:

    def __init__(self, username, password, soft_id='96001'):
        self.username = username
        self.password = password
        # 避免明文外泄，可以使用md5后的字符串
        # password = password.encode('utf8')
        # self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, codetype, im='./lib/verify/verify.png'):
        """
        im: 图片字节
        codetype: 验证码类型 参考 http://www.chaojiying.com/price.html
        """

        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        # 读取图片为二进制
        im = open(im, 'rb').read()
        files = {'userfile': ('verify.jpg', im)}
        try:
            r = requests.post('http://upload.chaojiying.net/Upload/Processing.php',
                              data=params, files=files,
                              headers=self.headers)
            rjson = r.json()
            if rjson['pic_str'] is None or str(rjson['pic_str']) == '':
                return None
            else:
                return str(rjson['pic_str'])
        except Exception as e:
            return None


if __name__ == '__main__':
    verify = Verify('wuqingfqng', '6e8ebd2e301f3d5331e1e230ff3f3ca5', '96001')
    # 普通图片解析
    print(verify.PostPic(1902, im='./lib/verify.png'))
